package com.itstudio.portal.job;


import com.itstudio.portal.entity.News;
import com.itstudio.portal.entity.Project;
import com.itstudio.portal.service.NewsService;
import com.itstudio.portal.service.ProjectService;
import com.itstudio.portal.utils.Const;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {

    final ProjectService projectService;

    final
    RedisTemplate redisTemplate;

    final NewsService newsService;

    public UpdateViewCountJob(ProjectService projectService, RedisTemplate redisTemplate, NewsService newsService) {
        this.projectService = projectService;
        this.redisTemplate = redisTemplate;
        this.newsService = newsService;
    }

    @Scheduled(cron = "0 0/3 * * * ?")
    public void updateViewCount(){
        Map<String, Integer> cacheMap = redisTemplate.opsForHash().entries(Const.PROJECT_VIEW_COUNT_KEY);
        Map<String, Integer> newsMap = redisTemplate.opsForHash().entries(Const.News_VIEW_COUNT_KEY);
        List<Project> projects = cacheMap.entrySet()
                .stream()
                .map(entry -> {
                    Project project = new Project();
                    project.setId(Long.valueOf(entry.getKey()));
                    project.setVisitCount(entry.getValue().longValue());
                    return project;
                })
                .collect(Collectors.toList());
        List<News> newsList = newsMap.entrySet()
                .stream()
                .map(entry -> {
                    News news = new News();
                    news.setId(Long.valueOf(entry.getKey()));
                    news.setViewCount(entry.getValue().longValue());
                    return news;
                })
                .collect(Collectors.toList());
        projectService.updateBatchById(projects);
        newsService.updateBatchById(newsList);
    }
}
